<template>
    <div class="dept-box">
        <div class="department-head">
            <div class="head-title">部门管理</div>
            <div class="department">
                <div class="dept-left">
                    <el-button type="success" plain @click="toggleRowExpansion">全部展开/收缩</el-button>
                </div>
                <div class="dept-right">
                    <el-button class="head-btn" type="primary" plain @click="addDepartment"><i
                            class=" iconfont icon-tianjia svg"></i>
                        创建部门</el-button>
                    <div class="option">
                        <el-input v-model="search" placeholder="请输入部门名称" class="input"
                            @keyup.enter.native="searchByTitel(search)" clearable>
                            <template #append>
                                <el-button class="iconfont icon-sousuo3" @click="searchByTitel(search)"></el-button>
                            </template>
                        </el-input>
                    </div>
                </div>

            </div>
        </div>

        <div class="table">
            <el-table :data="tableData" row-key="id" :tree-props="{ children: 'children' }" :expand-row-keys="expandRow"
                :indent="18" style="width: 100wh"
                :header-cell-style="{ 'text-align': 'left', background: '#f0f4f7', color: '#606266' }" max-height="430"
                :row-style="{ height: '5vh' }" ref="dataTreeList">
                <!-- <el-table-column type="selection" width="35" align="center" /> -->
                <el-table-column label="序号" type="index" width="100" align="left" />
                <el-table-column prop="deptName" label="部门名称" max-width="120" min-width="100px" align="left"
                    :show-overflow-tooltip="true" :cell-style="{ 'background': ' #' + color }">
                    <template #default="scope">
                        <span v-html="showData(scope.row.deptName, search)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="部门描述" max-width="120" min-width="80px" align="left"
                    :show-overflow-tooltip="true" />
                <el-table-column prop="createTime" label="创建时间" max-width="150" min-width="100px" align="left" />
                <el-table-column prop="status" label="状态" max-width="100" align="left">
                    <template #default="scope">
                        <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" inline-prompt
                            active-text="正常" inactive-text="禁用" @change="changeStatus(scope.row)"
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="left" min-width="90px">
                    <template #default="scope">
                        <el-tooltip class="box-item" effect="dark" content="添加新部门" placement="bottom">
                            <span>
                                <el-button type="success"
                                v-if="scope.row.deptLevel == 0 || scope.row.deptLevel == 1 || scope.row.deptLevel == 2"
                                circle class="iconfont icon-tianjia2" @click="addDept(scope.row)" />
                            </span>
                        </el-tooltip>
                        <el-tooltip class="box-item" effect="dark" content="添加学生到部门" placement="bottom">
                            <span>
                                <el-button type="success" v-if="scope.row.deptLevel == 3" circle class="iconfont icon-tianjia4"
                            @click="addStuAndCourse(scope.row)" />
                            </span>
                        </el-tooltip>
                        <el-button type="primary" circle class="iconfont icon-bianji"
                            @click="updateDeptBtn(scope.row)" />
                        <el-popconfirm width="120" confirm-button-text="确认" cancel-button-text="取消"
                            @confirm="deleteDept(scope.row)" title="确认删除?">
                            <template #reference>
                                <el-button type="danger" circle class="iconfont icon-shanchu"
                                    :disabled="Array.isArray(scope.row.children)" />
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog v-model="addDialog1" align-center width="40%" draggable class="dialog">
            <template #header class="dialog-header">
                <div v-if="addWords === 1">创建部门</div>
                <div v-if="addWords === 2">修改部门</div>
                <div v-if="addWords === 3">添加部门</div>
            </template>
            <el-form label-position="left" :model="deptData" style="max-width: 400px" label-width="auto"
                class="dialog-form">
                <el-form-item label="部门名">
                    <el-input v-model="deptData.deptName" class="dialog-input" placeholder="请输入部门名" />
                </el-form-item>
                <el-form-item label="部门描述">
                    <el-input v-model="deptData.description" class="dialog-input" placeholder="请输入描述" />
                </el-form-item>
                <el-form-item label="父部门">
                    <el-cascader :options="deptOptions" v-model="deptData.parentId" :props="{ checkStrictly: true }"
                        ref="cascaderRef" @change="orgChange" :placeholder="dialogPlaceholder" :show-all-levels="false"
                        filterable class="dialog-select" :disabled="disabledParent" />
                </el-form-item>
                <el-form-item label="部门状态">
                    <template #default>
                        <el-switch v-model="deptData.status" :active-value="1" :inactive-value="0" inline-prompt
                            active-text="正常" inactive-text="禁用"
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                    </template>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="insertDept" v-if="addWords === 1 || addWords === 3"
                        class="dialog-btn">确定</el-button>
                    <el-button type="primary" @click="upcreateTimePoint(deptData)" v-if="addWords === 2"
                        class="dialog-btn">保存</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="addDialog2" align-center width="40%" draggable class="dialog">
            <template #header class="dialog-header">
                <div>添加学生、课程</div>
            </template>
            <el-form label-position="left" :model="deptData" style="max-width: 400px" label-width="auto"
                class="dialog-form">
                <el-form-item label="课程">
                    <el-select-v2 v-model="classData.courseIds" :options="classData.courses" placeholder="请选择课程"
                        style="width: 280px" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3" />
                </el-form-item>
                <el-form-item label="学生">
                    <el-select-v2 v-model="classData.stuIds" :options="classData.userData" placeholder="请选择学生"
                        style="width: 280px" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3" />
                </el-form-item>


            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="addCls(classId)" class="dialog-btn">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>

</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { findNodesAPI, insertDeptAPI, deleteDeptAPI, updateDeptAPI, findDeptIdAPI, addClsAPI, getCourseListAPI, findByPageAPI } from '@/api/api.js'
import { ElMessage } from 'element-plus';


//表格数据
const tableData = ref([])
//
const dataTreeList = ref()
//添加部门弹框
const addDialog1 = ref(false)
//往班级中添加学生和课程弹框
const addDialog2 = ref(false)

//搜素框
const search = ref('')
//弹框标题
const addWords = ref(1)
//联级选择框
const cascaderRef = ref()
//部门名
const deptOptions = ref([])
//展开行
const expandRow = ref([])
//placeholder显示字
const dialogPlaceholder = ref('若为顶层请勿选择')
//是否禁用选择框
const disabled = ref(false)
const disabledParent = ref(false)
//新建部门锁定的颜色(未实现！！！！！！！)
const color = ref('')
//默认展开行 
const isExpand = ref(false)
//添加、更新操作数据
const deptData = ref({
    //部门id
    id: '',
    //父部门id
    parentId: '',
    //部门名
    deptName: '',
    //部门描述
    description: '',
    //状态
    status: 1,
    //部门级别
    deptLevel: '',
})
const classData = ref({
    //课程
    courseIds: [],
    //学生
    stuIds: [],
    //获取到的所有课程
    courses: [],
    //课程列表
    courseList: [],
    //用户
    userData: [],
})

onMounted(() => {
    //获取部门信息
    findNodes()
    //分页查询课程
    getCourseList()
    //获取用户列表
    findByPage()
})

//联级选择框选中后自动关闭(未实现)
const orgChange = () => {
    cascaderRef.value.popperVisible = false;
}
//分页查询课程
const getCourseList = async () => {
    await getCourseListAPI().then(res => {
        if (res.data.code == 200) {
            classData.value.courseList = res.data.data.list
            getCourseName(classData.value.courseList)
        }
    })
}
//获取课程名
const getCourseName = (courseList) => {
    for (let item of courseList) {
        classData.value.courses.push({
            label: item.courseName,
            value: item.id
        })
    }
}
//获取用户列表
const findByPage = async () => {
    await findByPageAPI(1, 1000).then(res => {
        // userData.value = res.data.data.list
        for (let i = 0; i < res.data.data.list.length; i++) {
            const element = res.data.data.list[i];
            classData.value.userData.push({
                label: element.name,
                value: element.stuId
            })
        }
    })
}
//获取所有部门信息
const findNodes = async () => {
    await findNodesAPI().then(res => {
        if (res.data.code==200) {
            tableData.value = res.data.data
            deptOptions.value = getTreeData(res.data.data)
        }
    })
}
//获取树形部门
const getTreeData = (data) => {
    for (let i = 0; i < data.length; i++) {
        data[i].label = data[i].deptName
        data[i].value = data[i].id
        if (data[i].children == null || data[i].children.length < 1) {
            data[i].children = undefined     //避免children为空的时候，下一级显示为空白
        }
        else {
            getTreeData(data[i].children)
        }
    }
    return data
}
//状态滑块改变
const changeStatus = (row) => {
    upcreateTimePoint(row)
    if (row.status == 0) {
        if (row.children) {
            changeChildrenStatus(row, row.status)
        }
    }
}
//父部门禁用连带子部门禁用
const changeChildrenStatus = (data, status) => {
    const rightStatus = status
    for (let item in data.children) {
        data.children[item].status = rightStatus
        upcreateTimePoint(data.children[item])
        if (data.children[item].children) {
            changeChildrenStatus(data.children[item], rightStatus)
        }
    }
}
//创建部门按钮
const addDepartment = () => {
    deptData.value = {}
    dialogPlaceholder.value = '若为顶层请勿选择'
    disabled.value = false
    disabledParent.value = false
    console.log(deptData.value, 'deptData.value1111');
    addDialog1.value = true
    addWords.value = 1
}
//扁平化的树形部门数据
const flattenedTableData = []
//创建部门
const insertDept = async () => {
    const data = deptData.value
    if (data.status) {
        data.status = data.status
    } else {
        data.status = 0
    }
    if (data.parentId) {
        if (data.parentId.length > 1) {
            data.parentId = Object.values(data.parentId).pop()
        }
        data.parentId = data.parentId.toString()
        getFlattenedData(tableData.value)
        for (let item of flattenedTableData) {
            if (item.id == data.parentId) {
                data.deptLevel = item.deptLevel + 1
            }
        }
    } else {
        data.parentId = 0
        data.deptLevel = 0
    }
    await insertDeptAPI(data).then(res => {
        if (res.data.code == 200) {
            ElMessage.success('添加成功')
            addDialog1.value = false
            findNodes()
            searchByTitel(data.deptName)
            color.value = 'red'
        }
        if (res.data.code == 222) {
            ElMessage.error(res.data.message)
        }
    })
}
//数据扁平化处理
const getFlattenedData = (data) => {
    data.forEach(element => {
        if (element.children) {
            getFlattenedData(element.children)
        }
        flattenedTableData.push(element)
    });

}
//添加部门按钮
const addDept = async (row) => {
    deptData.value = {}
    addDialog1.value = true
    addWords.value = 3
    await findDeptIdAPI(row.id).then(res => {
        const data = res.data.data
        dialogPlaceholder.value = data.deptName
        deptData.value.deptLevel = data.deptLevel + 1
        disabled.value = true
        disabledParent.value = true
        deptData.value.parentId = data.id
    })
}
//往班级中添加学生和课程按钮
const classId = ref()
const addStuAndCourse = (row) => {
    addDialog2.value = true
    classId.value = row.id
}
//班级添加学生和课程
const addCls = async (classId) => {
    const data = {}
    data.classId = Number(classId)
    data.courseIds = classData.value.courseIds
    data.stuIds = classData.value.stuIds
    console.log(data, 'data');
    await addClsAPI(data).then(res => {
        if (res.data.code == 200) {
            ElMessage.success('添加成功')
        } else {
            ElMessage.warning(res.data.message)
        }
        console.log(res);
    })
}

//按部门名查找
const searchByTitel = () => {
    isExpand.value = false
    toggleRowExpansion()
}
//搜索词高亮
const showData = (val, searchData) => {
    // 不区分大小写  const Reg = new RegExp(searchData, 'i');
    // 全局替换  const Reg = new RegExp(searchData, 'g');
    const Reg = new RegExp(searchData, 'ig');
    if (val) {
        // 注意 这里推荐使用正则占位符$& 不使用${searchData}  因为当这里使用正则表达式（i）不区分大小写时，
        // 如果你的文本是大写，搜索的关键字是小写，匹配结果会替换掉大写的文本
        const res = val.replace(Reg, `<span style="background-color: yellow;">$&</span>`);
        return res;
    }
}
// 切换数据表格树形展开
const toggleRowExpansion = () => {
    isExpand.value = !isExpand.value
    toggleRowExpansionAll(tableData.value, isExpand.value);
}
const toggleRowExpansionAll = (data, isExpand) => {
    data.forEach((item) => {
        dataTreeList.value.toggleRowExpansion(item, isExpand);
        if (item.children !== undefined && item.children !== null) {
            toggleRowExpansionAll(item.children, isExpand);
        }
    });
}
//删除部门
const deleteDept = async (row) => {
    const id = row.id
    console.log(row);
    await deleteDeptAPI(id).then(res => {
        if (res.data.code == 200) {
            ElMessage.success('删除成功')
            findNodes()
        }else{
            ElMessage.warning(res.data.message)
        }
    })
}
//更新部门按钮
const updateDeptBtn = (row) => {
    addDialog1.value = true
    addWords.value = 2
    deptData.value = row
}
//更新
const upcreateTimePoint = async (data) => {
    await updateDeptAPI(data).then(res => {
        if (res.data.code == 200) {
            ElMessage.success('更新成功')
            addDialog1.value = false
            findNodes()
        }else{
            ElMessage.warning(res.data.message)
        }
    })
}



</script>

<style lang="less">
.el-dialog__header {
    margin: 0 !important;
    background-color: #f8f8f8 !important;
    border-bottom: 1px solid #eeeeee;
}

.el-dialog__footer {
    background-color: #f0f4f7 !important;
    padding: 10px !important;
    border-top: 1px solid #eeeeee;
}
</style>
<style lang="less" scoped>
.dept-box {
    padding: 0;
    margin: 15px 0px 0 0;
    background-color: #fff;
    border-radius: 15px;

    .department-head {
        font-size: small;

        .head-title {
            font-size: 18px;
            font-weight: 550;
            color: grey;
            padding: 15px 10px 5px 10px;
        }

        .department {
            display: flex;
            justify-content: space-between;
            margin: 10px 35px;

            .dept-left {
                display: flex;
            }

            .dept-right {
                display: flex;

                .option {
                    display: flex;
                    margin: 0px 20px 5px 30px;

                    .input {
                        width: 240px;
                        max-height: 38px;
                        min-height: 35px;
                    }
                }

                .head-btn {
                    max-height: 38px;
                    min-height: 35px;

                    .svg {
                        padding: 2px;
                    }
                }
            }


        }

    }

    .dialog {
        width: 100px;

        .dialog-form {
            margin: 0 auto;

            .dialog-select {
                width: 220px;
            }

            .dialog-input {
                width: 280px;
            }

            .el-cascader {
                min-width: 280px;
            }
        }

        .dialog-footer {
            display: flex;
            justify-content: end;
            margin-right: 20px;

            .dialog-btn {
                margin-top: 0;
                width: 80px;
            }
        }


    }

    .table {
        max-height: 71.6vh;
        min-height: 71.6vh;
        margin: auto;
        width: 1250px;
        .el-button--success {
            margin-right:10px;
            // color: red;
        }
       
    }
}
</style>
